<?php

namespace api\modules\v1\models;

use api\func\func;
use Yii;
use api\common\models\Common;
use yii\web\NotFoundHttpException;
use yii\web\HttpException;
use yii\data\ActiveDataProvider;
use api\modules\v1\models\News;
use api\common\controllers\CommonController;
use api\common\models\Mar;
use yii\data\Pagination;
use yii\web\Link;
class Msg extends Common
{

    /**
     * @return array|string
     */
    public static function tableName()
    {
        return '{{%msg_app}}';
    }


    public function rules()
    {
        return [
            //['uid', 'required','message'=>'{attribute}不能为空'],

            //['message', 'required','message'=>'{attribute}不能为空'],

            //['type', 'required','message'=>'{attribute}不能为空'],

        ];
    }

    /*
     * 获取消息列表
     * @param $type
     * @return ActiveDataProvider
     */
    public function getList($type,$isread){

        $where = 'take_uid= '.Yii::$app->user->identity->id.' and type in ('.$type.')';
        if($type == 99){ //针对系统消息修改
            $time = date('Y-m-d H:i:s',strtotime('- 90 days'));
            $where = '(take_uid= '.Yii::$app->user->identity->id.' or take_uid = 0) and type in ('.$type.') and time >= "'.$time.'"';
        }

        if($isread !== ''){
            $where .= ' and isread = '.$isread;
        }

        $query =(new \yii\db\Query());
        $query->from('{{%msg_app}} as a');
        $query->select('a.*,b.head_img,b.username,b.nickname,b.phone');
        $query->innerJoin('{{%user_app}} as b','a.send_uid = b.id');
        $query->where($where);
        $query->orderBy('isread asc,time desc');

       // print_r($query->createCommand()->getRawSql());exit;

        $count = $query->count();
        $pagination = new Pagination(['totalCount' => $count]);
        $pagination->defaultPageSize = Yii::$app->params['page_size'];

        $data = $query->offset($pagination->offset)
            ->limit($pagination->limit)
            ->orderBy('isread asc,m_id desc')
            ->all();

        $this->serializePagination($pagination);
        if(count($data >0 )){
            foreach($data as $k=>$v){
                $data[$k]['head_img'] = $data[$k]['head_img'] != '' ? $data[$k]['head_img'] : Yii::$app->params['default_header'];//需求默认头像
                $data[$k]['nickname'] = $data[$k]['nickname'] != '' ? $data[$k]['nickname'] : func::replace_phone($data[$k]['phone']);
            }
        }

        $is_read = (new \yii\db\Query())
            ->from('{{%msg_app}} as a')
            ->innerJoin('{{%user_app}} as b','a.send_uid = b.id')
            ->where(['isread'=>1,'take_uid'=>Yii::$app->user->identity->id])
            ->count();
        $un_read = (new \yii\db\Query())
            ->from('{{%msg_app}} as a')
            ->innerJoin('{{%user_app}} as b','a.send_uid = b.id')
            ->where(['isread'=>0,'take_uid'=>Yii::$app->user->identity->id])
            ->count();

        //print_r((new \yii\db\Query())->from('{{%msg_app}}')->where(['isread'=>0,'take_uid'=>Yii::$app->user->identity->id])->createCommand()->getRawSql());exit;

        $_data = [];
        $_data['items'] = $data;
        $_data['_links'] = $this->linksEnvelope;
        $_data['_meta'] = $this->metaEnvelope;
        $_data['_meta']['_isread'] = $is_read;
        $_data['_meta']['_unread'] = $un_read;

        //echo $query->createCommand()->getRawSql();exit;
        return $_data;
    }

    public function getList_bak($type){
        $query =(new \yii\db\Query());
        $query->from('{{%msg_app}} as a');
        $query->select('a.*,b.head_img,b.username');
        $query->leftJoin('{{%user_app}} as b','a.send_uid = b.id');
        $query->where('take_uid= '.Yii::$app->user->identity->id.' and type in ('.$type.')');
        $query->orderBy('isread asc,time desc');
        $dataProvider = new ActiveDataProvider([
            'query' => $query,
            'pagination' => [
                'pageSize' => Yii::$app->params['page_size'],
            ],
        ]);
        //echo $query->createCommand()->getRawSql();exit;
        return $dataProvider;
    }


    /*
     * 获取消息详情
     * @return array|null|\yii\db\ActiveRecord
     * @throws NotFoundHttpException
     */
    public function getInfo(){
        $m_id = (int)Yii::$app->request->get('m_id');
        if($data = self::find()->where(['m_id'=>$m_id,'take_uid'=>Yii::$app->user->identity->id])->asArray()->one()){
            return $data;
        }else{
            throw new NotFoundHttpException('未找到记录.');
        }
    }



}
